package com.demo.web;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 生成图片验证码
 */
@WebServlet(urlPatterns = "/code")
public class ResponseDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 需要通过程序动态的生成一张图，将图片响应给客户端
        // 相当于找到一张画纸，并且在画纸上规定了画画的范围
        BufferedImage bufi = new BufferedImage(100, 40, BufferedImage.TYPE_INT_RGB);
        // 准备画笔，给图片上涂鸦
        Graphics2D g = (Graphics2D)bufi.getGraphics();
        // 用于获取随机数的对象
        Random r = new Random();
        // 设置画笔的颜色
        g.setColor(new Color(r.nextInt(101)+150,r.nextInt(100)+150,r.nextInt(100)+150));
        // 设置图片的背景颜色
        g.fillRect(0,0,100,40);

        // 给图片上写验证码数据
        g.setColor(Color.BLUE);
        // 设置字体，加粗，大小
        g.setFont(new Font("黑体",Font.BOLD,30));
        // 写内容
        String data = "1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
        int x = 10;
        // 定义一个容器，存储验证码数据
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i < 4 ; i++){
            g.setColor(new Color(r.nextInt(150),r.nextInt(150),r.nextInt(150)));
            int index = r.nextInt( data.length() );
            char ch = data.charAt(index);
            // 保存验证码上的数据
            sb.append(ch);
            int m = r.nextInt(91)-45;
            double theta = (Math.PI / 180) * m;
            g.rotate(theta , x , 35);
            g.drawString(ch+"", x, 35);
            g.rotate(-theta , x , 35);
            x += 20;
        }
        // 此时验证码已经生成，将验证码存储在session中
        req.getSession().setAttribute("serverImgCode",sb.toString());
        // 添加干扰线
        for(int i = 0 ; i < 10 ; i++){
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
            g.drawLine(r.nextInt(100),r.nextInt(40),r.nextInt(100),r.nextInt(40));
        }

        // 将这个图写到客户端
        resp.setContentType("image/jpeg");
        ImageIO.write(bufi,"jpeg", resp.getOutputStream());
    }
}
